<script setup lang="ts">
import type { FormInstance } from "element-plus";
import { useEventListener } from "@vueuse/core";
import { ElNotification } from "element-plus";
import { debounce } from "es-toolkit";
import { onUnmounted, reactive, ref } from "vue";
import Iphone from "~icons/ep/iphone";
import Keyhole from "~icons/ri/shield-keyhole-line";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { $t } from "@/plugins/i18n";
import { useUserStore } from "@/stores/user";
import Motion from "../utils/motion";
import { phoneRules } from "../utils/rules";
import { useVerifyCode } from "../utils/verifyCode";

const loading = ref(false);
const ruleForm = reactive({
    phone: "",
    verifyCode: "",
});
const ruleFormRef = ref<FormInstance>();
const { isDisabled, text, start: verifyStart } = useVerifyCode();

const onLogin = async (formEl: FormInstance | undefined) => {
    loading.value = true;
    if (!formEl) return;
    await formEl.validate((valid) => {
        if (valid) {
            // 模拟登录请求，需根据实际开发进行修改
            setTimeout(() => {
                ElNotification({
                    title: "登录成功",
                    message: $t("login.loginSuccess"),
                    type: "success",
                });
                loading.value = false;
            }, 2000);
        } else {
            loading.value = false;
        }
    });
};

function onBack() {
    useUserStore().SET_CURRENT_PAGE(0);
}

// 创建防抖的登录函数
const debouncedLogin = debounce(
    () => {
        onLogin(ruleFormRef.value);
    },
    500,
    { edges: ["leading"] },
);

// 监听键盘事件, 当按下回车键时触发登录
const cleanup = useEventListener(
    document,
    "keydown",
    ({ code }) => {
        if (["Enter", "NumpadEnter"].includes(code) && !loading.value) {
            // bugfix 每次按下回车键时都会创建一个新的防抖函数实例，这样防抖功能就无法正常工作。正确的做法是创建一个防抖函数的引用，然后重复使用它
            debouncedLogin();
        }
    },
);

onUnmounted(() => {
    cleanup();
});
</script>

<template>
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="phoneRules" size="large">
        <Motion>
            <el-form-item prop="phone">
                <el-input
                    v-model="ruleForm.phone"
                    clearable
                    :placeholder="$t('login.phone')"
                    :prefix-icon="useRenderIcon(Iphone)"
                />
            </el-form-item>
        </Motion>

        <Motion :delay="100">
            <el-form-item prop="verifyCode">
                <div class="w-full flex justify-between">
                    <el-input
                        v-model="ruleForm.verifyCode"
                        clearable
                        :placeholder="$t('login.smsVerifyCode')"
                        :prefix-icon="useRenderIcon(Keyhole)"
                    />
                    <el-button
                        :disabled="isDisabled"
                        class="ml-2"
                        @click="verifyStart(ruleFormRef, 'phone')"
                    >
                        {{
                            text.length > 0
                                ? text + $t("login.info")
                                : $t("login.getVerifyCode")
                        }}
                    </el-button>
                </div>
            </el-form-item>
        </Motion>

        <Motion :delay="150">
            <el-form-item>
                <el-button
                    class="w-full"
                    size="default"
                    type="primary"
                    :loading="loading"
                    @click="onLogin(ruleFormRef)"
                >
                    {{ $t("login.login") }}
                </el-button>
            </el-form-item>
        </Motion>

        <Motion :delay="200">
            <el-form-item>
                <el-button class="w-full" size="default" @click="onBack">
                    {{ $t("login.back") }}
                </el-button>
            </el-form-item>
        </Motion>
    </el-form>
</template>
